﻿using GameEntitySystem;

namespace ReserveInventory
{
    public class ReserveInventoryModLoader : ModLoader
    {
        public override void __ModInitialize()
        {
            base.__ModInitialize();
            //通过__ModInitialize来注册本ModLoader需要使用的两个接口DeadBeforeDrops和OnPlayerSpawned
            ModsManager.RegisterHook("DeadBeforeDrops", this);
            ModsManager.RegisterHook("OnPlayerSpawned", this);
        }
        public override void DeadBeforeDrops(ComponentHealth componentHealth, ref KillParticleSystem killParticleSystem, ref bool dropAllItems)
        {
            //设置dropAllItems = false，保证死亡时的物品都保留在尸体上面
            dropAllItems = false;
            ComponentPlayer componentPlayer = componentHealth.Entity.FindComponent<ComponentPlayer>();
            if (componentPlayer != null)
            {
                //禁用死亡时减半玩家的等级
                componentPlayer.PlayerData.ReduceLevelUponDeath = false;
            }
        }
        /// <summary>
        /// 生成玩家时执行
        /// </summary>
        /// <param name="spawnMode"></param>
        /// <param name="componentPlayer"></param>
        /// <param name="position"></param>
        /// <returns>这里始终返回false，后续的mod可以继续执行</returns>
        public override bool OnPlayerSpawned(PlayerData.SpawnMode spawnMode, ComponentPlayer componentPlayer, Vector3 position)
        {
            if (spawnMode != PlayerData.SpawnMode.Respawn) return false;//只对重生进行判定
            Entity deadPlayerEntity = componentPlayer.PlayerData.LastDeadPlayer;//获取在重生玩家时，上一次死掉的玩家，里面保留了玩家物品栏等大量信息
            if (deadPlayerEntity == null)
            {
                Log.Error("LastDeadPlayer = null，失败！");
                return false;
            }
            //转移常规背包中的物品，即将死人身上的物品转移到玩家身上。这一部分难度较高，看不懂的可以不管
            var components = deadPlayerEntity.FindComponents<ComponentInventoryBase>();
            foreach (var component in components)
            {
				if(componentPlayer.Entity.FindComponent(component.GetType(),null,false) is ComponentInventoryBase playerInventory)
				{
					Log.Information("开始转移" + component.GetType().Name);
					for(int s = 0; s < component.SlotsCount; s++)
					{
						if(playerInventory.m_slots[s].Value == 0 && playerInventory.m_slots[s].Count == 0)
						{
							playerInventory.m_slots[s].Value = component.GetSlotValue(s);
							playerInventory.m_slots[s].Count = component.GetSlotCount(s);
						}
					}
				}
			}
            //转移ComponentClothing，即将死人的衣物转移到玩家身上
            Log.Information("转移玩家衣物");
            ComponentClothing oldComponentClothing = deadPlayerEntity.FindComponent<ComponentClothing>();
            ComponentClothing newComponentClothing = componentPlayer.Entity.FindComponent<ComponentClothing>();
            for(int i = 0; i < oldComponentClothing.m_clothes.Count; i++)
                newComponentClothing.SetClothes((ClothingSlot)i, oldComponentClothing.m_clothes[(ClothingSlot)i]);
            return false;
        }
    }
}
